import React from 'react';
import './index.css';

class ImageTile extends React.PureComponent {
    render() {
        const { src, alt, confidence, isFullscreen } = this.props;
        console.log(`Rendering image: ${alt}`);
        if (!src) {
            return (
                <div className="image-container">
                    <span>等待信号</span>
                    <div className="image-name"><span>{`相机 ${alt}`}</span></div>
                </div>
            );
        }

        const containerClass = isFullscreen ? "image-container fullscreen" : "image-container";

        return (
            <div className={containerClass}>
                <img src={src} alt={`相机 ${alt}`} />
                <div className="image-name">
                    {isFullscreen ? (
                        <div className='abnormal'>
                            <span>{`相机 ${alt}`}</span><br />
                            <span>异常</span>
                        </div>
                    ) : (
                        <div>
                            <span>{`相机 ${alt}`}</span><br />
                            <span>正常</span>
                        </div>
                    )}
                    <div>
                        <span>可能性{confidence ? confidence.toFixed(6) : '--'}</span>
                    </div>
                </div>

            </div>
        );
    }
}

export default class ImageGrid extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            images: new Array(9).fill(null).map(() => ({
                src: null,
                result: null,
                confidence: 0,
                isFullscreen: false,
                abnormalTimeout: null,
            })),
        };
        this.websockets = [];
        this.timerID=null;
    }

    initializeWebSockets() {
        //连接websocket
        const baseWsUrl = 'ws://localhost:8764/cam';
        for (let i = 1; i <= 9; i++) {
            const ws = new WebSocket(`${baseWsUrl}${i}`);

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                this.updateImage(i - 1, `data:image/jpeg;base64,${data.frame}`, data.result, data.confidence);
            };

            ws.onerror = (error) => {
                console.error(`WebSocket error on camera ${i}:`, error);
            };

            ws.onclose = (event) => {
                console.log(`WebSocket for camera ${i} is closed now.`, event);
            };

            this.websockets.push(ws);
        }
    }

    componentDidMount() {
        this.initializeWebSockets();
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );
    }
    tick() {
        console.log("Tick");

    }
    componentWillUnmount() {
        debugger
        clearInterval(this.timerID);
        this.websockets.forEach((ws) => ws.close());
    }

    updateImage(index, src = null, result = null, confidence = 0) {
        //更新后端传来的帧
        const newImages = [...this.state.images];
        newImages[index].src = src;
        newImages[index].result = result;
        newImages[index].confidence = confidence;

        if (result === 1 && confidence > 99.99) {
            newImages[index].isFullscreen = true;

            if (newImages[index].abnormalTimeout) {
                clearTimeout(newImages[index].abnormalTimeout);
            }

            newImages[index].abnormalTimeout = setTimeout(() => {
                newImages[index].isFullscreen = false;
            }, 2000);
        }

        this.setState({ images: newImages });
    }

    render() {
        const abnormalImages = this.state.images.filter((image) => image.isFullscreen);
        const normalImages = this.state.images.filter((image) => !image.isFullscreen);

        return (
            <div className="grid">
                {abnormalImages.map((image, index) => (
                    <ImageTile
                        key={`abnormal-${index}`}
                        src={image.src}
                        result={image.result}
                        confidence={image.confidence}
                        alt={`${this.state.images.indexOf(image) + 1}`}
                        isFullscreen={true}
                    />
                ))}
                {normalImages.map((image, index) => (
                    <ImageTile
                        key={`normal-${index}`}
                        src={image.src}
                        result={image.result}
                        confidence={image.confidence}
                        alt={`${this.state.images.indexOf(image) + 1}`}
                        isFullscreen={false}
                    />
                ))}
            </div>
        );
    }
}
